import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        newproduct:[]
    },
    mutations: {
        addsame(state,payload){
            payload.count++
        },
        addnosame(state,payload){
            payload.checked = true;
            state.newproduct.push(payload)
        }
    },
    actions:{
        addCart(context,payload){
            return new Promise((resolve) => {
                let oldproduct = context.state.newproduct.find(item=>
                    item.iid === payload.iid
                )
                if(oldproduct){
                    context.commit('addsame',oldproduct)
                    resolve('商品数量+1')
                }else{
                    payload.count = 1
                    context.commit('addnosame',payload)
                    resolve('添加新的商品')
                }       
            })
        }
    },
    getters: {
        cartlength(state){
            return state.newproduct.length
        },
        cart(state){
            return state.newproduct
        }
    }
})

export default store